package com.servicecloud.consumer.controller;

import java.net.URI;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.servicecloud.entities.Dept;

/**
 * rabbon绕过eurake直接负载均衡访问提供者类，不标准的方式，只是知道rabbon有这个功能
 *
 * @author Gavin<br>
 *         2020年3月20日
 */
@RestController
@RibbonClient(name = "microservicecloud")
public class DeptController_Consumer {
	public static final String DEPT_REST_TOPIC = "microservicecloud";
	@Autowired
	private RestTemplate restTemplate;
	@Resource
	private HttpHeaders headers;
	@Resource
	private LoadBalancerClient loadBalancerClient;

	@RequestMapping(value = "/consumer/dept/get/{id}")
	public Dept get(@PathVariable("id") Long id) {
		ServiceInstance serviceInstance = this.loadBalancerClient.choose(DEPT_REST_TOPIC);
		System.out.println(
				"【*** ServiceInstance ***】host = " + serviceInstance.getHost() + "、port = " + serviceInstance.getPort()
						+ "、serviceId = " + serviceInstance.getServiceId() + "、uri = " + serviceInstance.getUri());
		URI deptUri = URI.create(
				String.format("http://%s:%s/dept/get/" + id, serviceInstance.getHost(), serviceInstance.getPort()));
		Dept dept = this.restTemplate
				.exchange(deptUri, HttpMethod.GET, new HttpEntity<Object>(this.headers), Dept.class).getBody();
		return dept;
	}

}
